package com.mine.dzq.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.mine.dzq.model.entity.StorageConfig;
import com.mine.dzq.service.StorageService;
import com.mine.dzq.service.config.ConfigService;
import com.mine.dzq.service.impl.OSSStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @Author Pudding
 * Spring配置类（初始化Bean）
 * @Date 2025/4/7 10:55
 */
@Configuration
public class OSSConfig {
    @Autowired
    private ConfigService configService;

    /**
     * ConfigService读取配置，然后在配置类中创建OSSClient的Bean
     *
     * @return
     */
    @Bean(destroyMethod = "shutdown") //关于OSSClient的关闭问题，OSS客户端需要在使用完毕后关闭，否则可能导致资源泄漏
    public OSS ossClient() {
        StorageConfig config = configService.getStorageConfig();
        if (config == null) {
            throw new IllegalStateException("OSS配置缺失");
        }
        return new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
    }

    /**
     * 使用条件装配，当配置了OSS的时候，自动创建OSSStorageService的Bean
     * 其他地方需要StorageService的时候，直接注入即可
     *
     * @param ossClient
     * @return
     */
    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) //强制单例模式：即使多次注入也返回同一个实例
    public StorageService storageService(OSS ossClient) {
        StorageConfig config = configService.getStorageConfig();
        return new OSSStorageService(ossClient, config.getBucketName());
    }
}